#import "FiveDifferent.h"

const NSInteger kNumOfPics = 7;
const NSInteger kNumOfImages = 6;
const NSInteger kRows = 3;


@interface FiveDifferent ()


@property BOOL isGameOver;
@property NSMutableArray* images;
@property NSInteger imageForChange;
@property NSArray* colors;

@end


@implementation FiveDifferent

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setName:@"Five Different Shapes"];
        [self setType:reaction];
        self.images=[[NSMutableArray alloc]init];
        self.ruleOfTheGame = @"5 different shapes!";
    }
    return self;
}

-(void)draw{
    [self removeAllComponents];
    
    
    for (int coloum=0; coloum<3; coloum++) {
        for (int row=0; row<2; row++) {
            
            int imageNumber=arc4random_uniform(6);
            NSString* imageString=[NSString stringWithFormat:@"FiveDifferent%d",imageNumber+2];
            NSInteger imageSize=(kScreenWidth-kHeighMargin)/kRows;
            self.images[self.imageForChange]=imageString;
            int transform=arc4random_uniform(4);
            CGFloat trans=1.57 * transform;
            ImageGameComponent* image=[[ImageGameComponent alloc]initWithName:imageString andFrame:CGRectMake(kWidthMargin+(coloum*imageSize), kHeighMargin+(row*imageSize), imageSize, imageSize)andTrans:trans];
            [self addComponents:image];
            self.imageForChange++;
        }
    }
    
    self.imageForChange=0;
    if ([self isRight]) {
        [self draw];
    }
}

-(void)play{
    [self draw];
    
   [NSTimer scheduledTimerWithTimeInterval: 1                                                 target: self selector:@selector(changeImage:)userInfo: nil repeats:YES];
    
}


//send notification
-(void)changeImage:(NSTimer*)timer{
    if (self.isGameOver==YES) {
        [timer invalidate];
    }
    else{
        [self changeAnImage];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"SomeGames" object:self userInfo:nil];
        
    }
    
}


//change image
-(void)changeAnImage{
    int imageNumber=arc4random_uniform(7);
    NSString* imageString=[NSString stringWithFormat:@"FiveDifferent%d",imageNumber+1];
    
    self.images[self.imageForChange]=imageString;
    int transform=arc4random_uniform(4);
    ImageGameComponent* newComp=self.components[self.imageForChange];
    newComp.name=imageString;
    self.imageForChange++;
    
    if (self.imageForChange == 6) {
        self.imageForChange=0;
    }
    
    
}


-(BOOL) isRight {
    return [self isThereFiveDifferent];
}

-(BOOL) isThereFiveDifferent {
    NSCountedSet* set = [[NSCountedSet alloc] init];
    for(NSInteger i = 0;i< kNumOfImages ; ++i) {
        [set addObject:((ImageGameComponent*)(self.components[i])).name];
    }
    return [set count] >= 5;
}

-(void)gameOver{
    self.isGameOver=YES;
}

@end
